package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"strings"
	"time"
)

var MysqlDB *gorm.DB

type JSONTime struct {
	time.Time
}

type CommonModel struct {
	Id        uint64   `gorm:"type:int(11) unsigned NOT NULL AUTO_INCREMENT;primaryKey;" json:"id"`
	DeletedAt JSONTime `gorm:"type:timestamp;" json:"deleted_at"`
	UpdatedAt JSONTime `gorm:"type:timestamp;not null;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0)" json:"updated_at"`
	CreatedAt JSONTime `gorm:"index;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"created_at"`
}

func InitWithDsn(dsn string) {
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("数据库连接失败，" + fmt.Sprintf("%s\n", err.Error()) + dsn)
	}
	MysqlDB = db
}


func Where(db *gorm.DB, condition bool, query string, args ...interface{}) *gorm.DB {
	if condition {
		db = db.Where(query, args...)
	}
	return db
}

func Like(keyword string) string {
	if keyword == "" {
		return ""
	}
	return strings.Join([]string{"%", keyword, "%"}, "")
}

func OffsetAndLimit(db *gorm.DB, offset, limit int) *gorm.DB {
	if offset != 0 {
		db = db.Offset(offset)
	}
	if limit != 0 {
		db = db.Limit(limit)
	}
	return db
}

// Expr generate raw SQL expression, for example:
//     DB.Model(&product).Update("price", gorm.Expr("price * ? + ?", 2, 100))
func Expr(expression string, args ...interface{}) clause.Expr {
	return gorm.Expr(expression, args...)
}

// 分页
func Pagination(db *gorm.DB, page, perPage int) *gorm.DB {
	if page <= 0 {
		page = 1
	}
	if perPage <= 0 {
		perPage = 20
	}

	db = db.Offset((page - 1) * perPage)
	db = db.Limit(perPage)
	return db
}

func OrderSort(sort *bool) string {
	if sort == nil || *sort {
		return "DESC"
	}
	return "ASC"
}